package com.campusbackend.service.impl;

import com.campusbackend.entity.TeamExperts;
import com.campusbackend.entity.Teams;
import com.campusbackend.mapper.TeamExpertsMapper;
import com.campusbackend.mapper.TeamsMapper;
import com.campusbackend.service.TeamExpertsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 队伍专家表 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-07-26
 */
@Service
public class TeamExpertsServiceImpl extends ServiceImpl<TeamExpertsMapper, TeamExperts> implements TeamExpertsService {

    @Autowired
    private TeamExpertsMapper teamExpertsMapper;
    
    @Autowired
    private TeamsMapper teamsMapper;

    @Override
    @Transactional
    public boolean joinTeam(Long teamId, Long expertId) {
        // 1. 验证队伍是否存在
        Teams team = teamsMapper.selectById(teamId);
        if (team == null) {
            throw new RuntimeException("队伍不存在");
        }
        
        // 2. 验证队伍状态是否正常
        if (team.getStatus() != 1) {
            throw new RuntimeException("队伍状态异常，无法入驻");
        }
        
        // 3. 验证教师不能入驻自己创建的队伍
        if (team.getInstructorId().equals(expertId)) {
            throw new RuntimeException("不能入驻自己创建的队伍");
        }
        
        // 4. 验证教师是否已经入驻该队伍
        int existCount = teamExpertsMapper.checkExpertExists(teamId, expertId);
        if (existCount > 0) {
            throw new RuntimeException("您已经入驻该队伍，无需重复操作");
        }
        
        // 5. 创建入驻记录
        TeamExperts teamExpert = new TeamExperts();
        teamExpert.setTeamId(teamId);
        teamExpert.setExpertId(expertId);
        teamExpert.setJoinStatus((byte) 1); // 1-已入驻
        teamExpert.setJoinTime(LocalDateTime.now());
        teamExpert.setCreateTime(LocalDateTime.now());
        teamExpert.setUpdateTime(LocalDateTime.now());
        
        // 6. 插入数据
        int result = teamExpertsMapper.insertExpert(teamExpert);
        
        return result > 0;
    }
} 